package com.heatup.apt.management.util;

import java.awt.Image;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * excel导出工具类
 * @author Earvin
 *
 */
public class ExcelDocumentor {
	private Logger log = LoggerFactory.getLogger(ExcelDocumentor.class);
	
	
	
    /**   
	*   @param   inputFile   输入模板文件路径   
	*   @param   outputFile   输入文件存放于服务器路径   
	*   @param   dataList   待导出数据   
	*   @throws   Exception   
	*   @roseuid:   
	*/   
	public void exportExcelFile(String inputFile, String outputFile, List dataList) throws Exception {
		// 用模板文件构造poi
		POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(inputFile));
		// 创建模板工作表
		HSSFWorkbook templatewb = new HSSFWorkbook(fs);
		// 直接取模板第一个sheet对象
		HSSFSheet templateSheet = templatewb.getSheetAt(1);
		// 得到模板的第一个sheet的第一行对象 为了得到模板样式
		HSSFRow templateRow = templateSheet.getRow(0);
		// HSSFSheet timplateSheet = templatewb.getSheetAt(1);
		// 取得Excel文件的总列数
		int columns = templateSheet.getRow((short) 0).getPhysicalNumberOfCells();
		// 创建样式数组
		HSSFCellStyle styleArray[] = new HSSFCellStyle[columns];
		// 一次性创建所有列的样式放在数组里
		for (int s = 0; s < columns; s++) {
			// 得到数组实例
			styleArray[s] = templatewb.createCellStyle();
		}
		// 循环对每一个单元格进行赋值
		// 定位行
		for (int rowId = 1; rowId < dataList.size(); rowId++) {
			// 依次取第rowId行数据 每一个数据是valueList
			List valueList = (List) dataList.get(rowId - 1);
			// 定位列
			for (int columnId = 0; columnId < columns; columnId++) {
				// 依次取出对应与colunmId列的值
				// 每一个单元格的值
				String dataValue = (String) valueList.get(columnId);
				// 取出colunmId列的的style
				// 模板每一列的样式
				HSSFCellStyle style = styleArray[columnId];
				// 取模板第colunmId列的单元格对象
				// 模板单元格对象
				HSSFCell templateCell = templateRow.getCell((short) columnId);
				// 创建一个新的rowId行 行对象
				// 新建的行对象
				HSSFRow hssfRow = templateSheet.createRow(rowId);
				// 创建新的rowId行 columnId列 单元格对象
				// 新建的单元格对象
				HSSFCell cell = hssfRow.createCell((short) columnId);
				// 如果对应的模板单元格 样式为非锁定
				if (!templateCell.getCellStyle().getLocked()) {
					// 设置此列style为非锁定
					style.setLocked(false);
					// 设置到新的单元格上
					cell.setCellStyle(style);
				}
				// 否则样式为锁定
				else {
					// 设置此列style为锁定
					style.setLocked(true);
					// 设置到新单元格上
					cell.setCellStyle(style);
				}
				// 设置编码
			//	cell.setEncoding(HSSFCell.ENCODING_UTF_16);
				
				// Debug.println("dataValue : " + dataValue);
				// 设置值 统一为String
				cell.setCellValue(dataValue);
			}
		}
		// 设置输入流
		FileOutputStream fOut = new FileOutputStream(outputFile);
		// 将模板的内容写到输出文件上
		templatewb.write(fOut);
		fOut.flush();
		// 操作结束，关闭文件
		fOut.close();

	}

	public void exportTable(List<?> entities, Map<String, String> columns,
			File target) {
		try {
			FileOutputStream fos = new FileOutputStream(target);
			BufferedOutputStream out = new BufferedOutputStream(fos);
			exportTable(entities, columns, out);
			out.close();
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
	}
	
	public void exportTable(List<?> entities, Map<String, String> columns,
			OutputStream out) {
		if (entities != null && entities.size() > 0) {
			// 创建新的Excel 工作簿
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFFont headerFont = workbook.createFont();
			headerFont.setFontHeightInPoints((short)10);
			headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			headerFont.setColor(IndexedColors.BLACK.getIndex());
			headerFont.setFontName("宋体");
			
			HSSFCellStyle headerStyle = workbook.createCellStyle();
			headerStyle.setFont(headerFont);
			headerStyle.setBorderLeft(CellStyle.BORDER_THIN);
			headerStyle.setBorderRight(CellStyle.BORDER_THIN);
			headerStyle.setBorderTop(CellStyle.BORDER_THIN);
			headerStyle.setBorderBottom(CellStyle.BORDER_THIN);
			headerStyle.setAlignment(CellStyle.ALIGN_CENTER);
			headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
			// 创建第二种字体样式（用于值）
			HSSFFont dataFont = workbook.createFont();
			dataFont.setFontHeightInPoints((short) 10);
			dataFont.setColor(IndexedColors.BLACK.getIndex());
			dataFont.setFontName("宋体");
			HSSFCellStyle dataStyle = workbook.createCellStyle();
			dataStyle.setFont(dataFont);
			dataStyle.setBorderLeft(CellStyle.BORDER_THIN);
			dataStyle.setBorderRight(CellStyle.BORDER_THIN);
			dataStyle.setBorderTop(CellStyle.BORDER_THIN);
			dataStyle.setBorderBottom(CellStyle.BORDER_THIN);
			dataStyle.setAlignment(CellStyle.ALIGN_CENTER);
			dataStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
			
			
			// 在Excel工作簿中建一工作表，其名为缺省值
			HSSFSheet sheet = workbook.createSheet();
			//设置默认宽度和高度
			sheet.setDefaultColumnWidth(20);  
			sheet.setDefaultRowHeightInPoints(20);  
			
			List<String> keys = DocumentHelper.getKeysFromObject(columns);
			writeTableHead(sheet, columns,headerStyle); // 输出标题
			for (int i = 0; i < entities.size(); i++) {
				Map<String, Object> values = null;
				if (entities.get(i) instanceof Map) {
					values = (Map<String, Object>) entities.get(i);
				} else {
					values = DocumentHelper.getGetMethodInfo(entities.get(i));
				}
				writeObjectToRow(sheet, keys, values, i + 1,dataStyle);
			}
			try {
				// 把相应的Excel 工作簿存盘
				workbook.write(out);
				out.flush();
			} catch (IOException e) {
				log.error("保存文档失败: ",e);
			}
		}
	}
	/**
	 * 设置表格标题
	 * @param sheet
	 * @param columns
	 * @param style
	 */
	
	private void writeTableHead(HSSFSheet sheet, Map<String, String> columns,HSSFCellStyle style) {
		Object[] keys = columns.keySet().toArray();
		HSSFRow row = sheet.createRow(0);
		for (int i = 0; i < keys.length; i++) {
			String columnName = columns.get(keys[i]).toString();
			HSSFCell cell = row.createCell((short) i);
			cell.setCellType(HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(new HSSFRichTextString(columnName));
			cell.setCellStyle(style);
		}
	}
	
	/**
	 * 将Map对象输出到特定行
	 * @param sheet 工作薄
	 * @param keys
	 * @param obj
	 * @param rowId
	 */
	private void writeObjectToRow(HSSFSheet sheet, List<String> keys,
			Map<String, Object> obj, int rowId,HSSFCellStyle style) {
		HSSFRow row = sheet.createRow(rowId);
		for (int i = 0; i < keys.size(); i++) {
			HSSFCell cell = row.createCell((short) i);
			// 在单元格中设置内容
			setCellValue(cell, obj.get(keys.get(i)));
			cell.setCellStyle(style);
		}
	}
	
	/**
	 * 为单元格设置值
	 * @param obj
	 */
	private void setCellValue(HSSFCell cell, Object obj) { // 未完成
		if (obj.getClass() == Boolean.class || obj.getClass() == Boolean.TYPE) {
			cell.setCellType(HSSFCell.CELL_TYPE_BOOLEAN);
			cell.setCellValue((Boolean) obj);
		} else if (obj.getClass() == Integer.class
				|| obj.getClass() == Integer.TYPE
				|| obj.getClass() == Short.class
				|| obj.getClass() == Short.TYPE
				|| obj.getClass() == Double.class
				|| obj.getClass() == Double.TYPE
				|| obj.getClass() == Float.class
				|| obj.getClass() == Float.TYPE || obj.getClass() == Long.class
				|| obj.getClass() == Long.TYPE) {
			cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cell.setCellValue(new HSSFRichTextString(obj.toString()));
		} else if(obj.getClass()==Image.class){
			
		}
		else {
			cell.setCellType(HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(new HSSFRichTextString(obj.toString()));
		}
	}
}
